﻿using AFanDa.BLL.BaseService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AFanDa.Dto.Base;
using AFanDa.Dto.EF;

namespace AFanDa.BLL.BLLService
{
    public class LoginService : ResultService
    {
        BaseAdminService _baseAdminService = null;
        BaseLoginLogsService _baseLoginLogsService = null;
        BaseWxUserService _baseWxUserService = null;
        public LoginService()
        {
            _baseAdminService = new BaseAdminService();
            _baseLoginLogsService = new BaseLoginLogsService();
            _baseWxUserService = new BaseWxUserService();
        }


        public IQueryable<Dto.EF.Admin> CheckLogin(string code)
        {
            var iq = _baseAdminService.QueryAll(d => d.ACode == code);
            return iq;
        }


        /// <summary>
        /// 验证登录
        /// </summary>
        /// <param name="Account"></param>
        /// <param name="Password"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public ApiResult Logins(string Account, string Password, string code)
        {
            string key = Common.Config.GetKey("LoginKey");
            string pwd = Common.EncryptUtil.LoginMd5(Password, key);

            var iq = _baseAdminService.QueryAll(d => d.Account == Account && d.Password == pwd);

            if (iq.Any())
            {
                var user = iq.Single();
                if (user.status == 0)
                {
                    user.ACode = code;
                    var result = _baseAdminService.SaveChange();

                    if (result > 0)
                    {
                        LoginLogs loginLogs = new LoginLogs()
                        {
                            LLID = Common.Config.GUID(),
                            LLUID = user.Aid,
                            LLCode = code,
                            LLConnectionID = null,
                            LLCreateTime = DateTime.Now,
                            LLIsOut = 0
                        };
                        _baseLoginLogsService.Add(loginLogs);
                        _baseLoginLogsService.SaveChange();

                    }

                    return GetResult(result > 0 ? ApiCode.ok : ApiCode.fail, result > 0 ? "登录成功" : "登录失败");
                }

                return GetResult(ApiCode.fail, message: "你的账号已被封禁");


            }

            return GetResult(code: ApiCode.fail, message: "账号或者密码错误");

        }
        /// <summary>
        /// 根据 code 获取用户信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public IQueryable<Admin> getUserByCode(string code)
        {
            var iq = _baseAdminService.QueryAll(d => d.ACode == code);
            return iq;
        }
        /// <summary>
        /// 获取 前台用户信息
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public IQueryable<WxUser> GetWxUser(string phone)
        {
            var iq = _baseWxUserService.QueryAll(d => d.UPhone == phone);
            return iq;
        }

        public ApiResult SetConnection(string code, string connectionid)
        {
            var iq = _baseLoginLogsService.QueryAll(d => d.LLCode == code);

            if (iq.Any())
            {
                var log = iq.Single();
                log.LLConnectionID = connectionid;
                _baseLoginLogsService.Update(log);



                var list = _baseLoginLogsService.QueryAll(d => d.LLUID == log.LLUID && d.LLCode != code && d.LLIsOut == 0);

                foreach (var item in list)
                {
                    item.LLIsOut = 1;
                };

                _baseLoginLogsService.UpdateRange(list);

                var ids = list.Select(o => o.LLConnectionID).ToList();

                var result = _baseLoginLogsService.SaveChange();

                return GetResult(result > 0 ? ApiCode.ok : ApiCode.fail, data: ids);

            }
            else
            {
                return GetResult(ApiCode.fail);

            }

        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public ApiResult WxZhuCe(Dto.Request.WxUserRequestDto dto)
        {

            var iq = _baseWxUserService.QueryAll(d => d.UPhone == dto.phone);
            if (!iq.Any())
            {

                _baseWxUserService.Add(new WxUser()
                {
                    Uid = Common.Config.GUID(),
                    Createtime = DateTime.Now,
                    Level = 0,
                    status = 0,
                    Uavatar = "",
                    Umoney = 0,
                    UMsg = dto.message,
                    UPhone = dto.phone,
                    UName = dto.phone,
                    USex = 0,
                    Uvip = "",
                    ULastLoginTime = DateTime.Now

                });

                _baseWxUserService.SaveChange();

                return new ApiResult()
                {
                    code = ApiCode.ok,
                    message = "注册成功"
                };
            }
            else
            {
                var user = iq.Single();

                user.Createtime = DateTime.Now;
                user.UMsg = dto.message;
                _baseWxUserService.Update(user);
                _baseWxUserService.SaveChange();

                return new ApiResult()
                {
                    code = ApiCode.ok,
                    message = "注册成功"
                };
            }
        }

        /// <summary>
        /// 前台用户登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public ApiResult WxLogin(Dto.Request.WxUserRequestDto dto)
        {

            if (dto.message == "" || dto.message == null)
            {
                return new ApiResult()
                {
                    code = ApiCode.fail,
                    message = "无效的验证码"
                };
            }
            var Loginiq = _baseWxUserService.QueryAll(d => d.UPhone == dto.phone && d.UMsg == dto.message);

            if (Loginiq.Any())
            {

                var user = Loginiq.Single();

                //if (user.Createtime.AddMinutes(5) < DateTime.Now) {
                //    return new ApiResult()
                //    {
                //        code = ApiCode.fail,
                //        message = "验证码过期"
                //    };
                //}

                    return new ApiResult()
                    {
                        code = ApiCode.ok,
                        message = "登录成功"
                    };
            }
            return new ApiResult()
            {
                code = ApiCode.fail,
                message = "验证码错误"
            };


        }
        /// <summary>
        /// 获取用户个人中心信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // 获取前台用户信息

        public ApiResult GetWxUserInfo(string id)
        {
            var iq = _baseWxUserService.QueryAll(d => d.Uid == id);

            if (iq.Any())
            {
                var user = iq.Single();

                Dto.Reponse.WxUserResponseDto dto = new Dto.Reponse.WxUserResponseDto()
                {

                    id = user.Uid,
                    name = user.UName,
                    phone = user.UPhone,
                    money = user.Umoney,
                    allorder = user.Orders.Where(d => d.OState == 0).Count()
                };
                decimal? moenys = 0;
                user.Orders.ToList().ForEach(d =>
                {
                    moenys += d.OPaidInMoney == null ? 0 : d.OPaidInMoney;
                });

                dto.allmoney = moenys;


                return new ApiResult()
                {
                    code = ApiCode.ok,
                    message = "获取个人信息",
                    data = dto
                };

            }
            return new ApiResult()
            {
                code = ApiCode.fail,
                message = "用户不存在"

            };
        }

    }
}
